package com.myphoto.business.photo.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.myphoto.base.mybatis.photo.dao.PhoneListDao;
import com.myphoto.base.mybatis.photo.entity.PhoneListEntity;
import com.myphoto.business.photo.model.PhoneListModel;
import com.myphoto.business.photo.model.PhoneModel;
import com.myphoto.business.photo.service.PhoneService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class PhoneServiceImpl implements PhoneService {

    @Resource
    private PhoneListDao phoneListDao;

    @Override
    public PhoneListModel loadPhoneList() throws Exception {
        LambdaQueryWrapper<PhoneListEntity> lqw = Wrappers.lambdaQuery();
        PhoneListModel phoneListModel = new PhoneListModel();
        List<PhoneModel> phoneModelList = new ArrayList<PhoneModel>();
        List<PhoneListEntity> phoneList = phoneListDao.selectList(lqw);
        for(PhoneListEntity phone : phoneList){
            PhoneModel model = new PhoneModel();
            BeanUtils.copyProperties(phone,model);
            phoneModelList.add(model);
        }
        phoneListModel.setPhoneModelList(phoneModelList);
        return phoneListModel;
    }

    @Override
    @Transactional
    public void uploadPhoneList(PhoneListModel phoneList) throws Exception {
        LambdaQueryWrapper<PhoneListEntity> lqw = Wrappers.lambdaQuery();
        phoneListDao.delete(lqw);
        for(PhoneModel model : phoneList.getPhoneModelList()){
            PhoneListEntity entity = new PhoneListEntity();
            BeanUtils.copyProperties(model,entity);
            phoneListDao.insert(entity);
        }
    }

}
